import os
import sys
import time
from functools import wraps

from loguru import logger

from app.globals import env

LOG_FORMAT = '[<green>{time:MM-DD HH:mm:ss.SSSSSS}</green> <lvl>{level}</lvl> line: {line}] ' \
             '{name} {function} {message}'

logfile = os.environ.get('LOGFILE', 'radar.log')
logger.remove()
logger.add(sys.stdout, backtrace=True, format=LOG_FORMAT, level=env.log_level)


# logger.add(logfile, rotation="10 MB", retention="3 days", backtrace=True, format=LOG_FORMAT)


def with_timing(func):
    @wraps(func)
    def calc_wasted_time(*args, **kwargs):
        t1 = time.time()
        func_return = func(*args, **kwargs)
        t2 = time.time()
        diff = (t2 - t1) * 1000
        logger.info(f'{func.__module__} {func.__name__} elapsed: {diff} ms')
        return func_return

    return calc_wasted_time


def log_except(func):
    @wraps(func)
    def wrap(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            logger.exception(e)

    return wrap
